package com.xiaoyy.app.extend.integration.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.api.request.OapiGetJsapiTokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiGettokenJsonRequest;
import com.alibaba.xxpt.gateway.shared.api.request.OapiMoziEmployeeGetByMobileRequest;
import com.alibaba.xxpt.gateway.shared.api.response.OapiGetJsapiTokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiGettokenJsonResponse;
import com.alibaba.xxpt.gateway.shared.api.response.OapiMoziEmployeeGetByMobileResponse;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentGetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.alibaba.xxpt.gateway.shared.client.http.api.OapiSpResultContent;
import com.xiaoyy.app.extend.common.vo.QueryZzdTokenVO;
import com.xiaoyy.app.extend.common.vo.ZzdEmployeeVO;
import com.xiaoyy.app.extend.integration.ZzdIntegration;
import com.xiaoyy.core.common.exception.AppException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class ZzdIntegrationImpl implements ZzdIntegration {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    String domainName = "openplatform.dg-work.cn";
    private ExecutableClient executableClient;
    @Override
    public String getEmployeeIdByMobile(ZzdEmployeeVO vo) {
        doInitExecutableClient(vo.getAppKey(),vo.getAppSecret());
        String accountId = "";
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/mozi/employee/get_by_mobile");
        OapiMoziEmployeeGetByMobileRequest oapiMoziEmployeeGetByMobileRequest = new OapiMoziEmployeeGetByMobileRequest();
        //手机区号
        oapiMoziEmployeeGetByMobileRequest.setAreaCode(vo.getAreaCode());
        //租户ID
        oapiMoziEmployeeGetByMobileRequest.setTenantId(vo.getTenantId());
        //账号类型
        oapiMoziEmployeeGetByMobileRequest.setNamespace(vo.getNamespace());
        //手机号
        oapiMoziEmployeeGetByMobileRequest.setMobile(vo.getMobile());
        //获取结果
        OapiMoziEmployeeGetByMobileResponse apiResult = null;
        try{
            apiResult = intelligentGetClient.get(oapiMoziEmployeeGetByMobileRequest);
        }catch (Exception e){
            throw new AppException("调用get_by_mobile接口失败:"+e.getMessage());
        }
        if(Objects.nonNull(apiResult) && apiResult.getSuccess()){
            OapiSpResultContent content = apiResult.getContent();
            if(!content.getSuccess()){
                throw new AppException("调用get_by_mobile接口失败："
                        +content.getResponseCode()+"|"+content.getResponseMessage());
            }
            String api ="/mozi/employee/listEmployeeAccountIds";
            PostClient postClient = executableClient.newPostClient(api);
            //设置参数
            JSONObject data = null;
            if(StringUtils.isNotBlank(apiResult.getContent().getData())){
                try{
                    data = JSON.parseObject(apiResult.getContent().getData());
                }catch (Exception e){
                    logger.error("调用accountId接口失败",e);
                }
            }else {
                throw new AppException("调用接口异常");
            }
            postClient.addParameter("employeeCodes",data.getString("employeeCode"));
            postClient.addParameter("tenantId", vo.getTenantId().toString());
            //调用API
            try{
                String Result = postClient.post();
                if(JSON.parseObject(Result).getBoolean("success")){
                    JSONObject jsonObject = JSON.parseObject(Result);
                    JSONArray array =  JSON.parseObject(Result).getJSONObject("content").getJSONArray("data");
                    // List list = new ArrayList();
                    for (int i = 0; i <array.size() ; i++) {
                        JSONObject ob = (JSONObject) array.get(i);
                        accountId = ob.getString("accountId");
                    }
                    //employeeCode = JSON.parseObject(Result).getJSONObject("content").getJSONObject("data").getString("accountId");
                }else{
                    return "系统异常！";
                }
            }catch (Exception e){
                e.printStackTrace();
                throw  new AppException("调用accountId接口失败！");
            }
        }else{
            if(Objects.isNull(apiResult)){
                throw new AppException("调用get_by_mobile接口失败:返回为空");
            }else{
                throw new AppException("调用get_by_mobile接口失败:"+apiResult.getMessage());
            }
        }
        return accountId ;
    }

    @Override
    public String getAccessToken(QueryZzdTokenVO vo) {
        doInitExecutableClient(vo.getAppKey(),vo.getAppSecret());
        String accessToken = "";
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/gettoken.json");
        OapiGettokenJsonRequest oapiGettokenJsonRequest = new OapiGettokenJsonRequest();
        //应用的唯一标识key
        oapiGettokenJsonRequest.setAppkey(vo.getAppKey());
        //应用的密钥
        oapiGettokenJsonRequest.setAppsecret(vo.getAppSecret());
        //获取结果
        try{
            //获取accessToken
            OapiGettokenJsonResponse apiResult = intelligentGetClient.get(oapiGettokenJsonRequest);
            if(apiResult.getSuccess()){
                //调用鉴权获取鉴权accessToken
                intelligentGetClient = executableClient.newIntelligentGetClient("/get_jsapi_token.json");
                OapiGetJsapiTokenJsonRequest oapiGetJsapiTokenJsonRequest = new OapiGetJsapiTokenJsonRequest();
                oapiGetJsapiTokenJsonRequest.setAccessToken(accessToken = JSON.parseObject(apiResult.getContent().getData()).getString("accessToken"));
                //获取结果
                try{
                    OapiGetJsapiTokenJsonResponse Result = intelligentGetClient.get(oapiGetJsapiTokenJsonRequest);
                    if(apiResult.getSuccess()){
                        accessToken = JSON.parseObject(Result.getContent().getData()).getString("accessToken");
                    }else{
                        return "系统异常！";
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw  new AppException("调用鉴权接口失败！");
                }
            }else{
                return "系统异常！";
            }
        }catch (Exception e){
            e.printStackTrace();
            throw  new AppException("调用接口失败！");
        }
        return accessToken ;
    }

    private void doInitExecutableClient(String appKey,String appSecret){
        if(Objects.nonNull(executableClient)){
            return;
        }
        executableClient = ExecutableClient.getInstance();
        //DomainName不同环境对应不同域名，示例为sass域名 ewm.rsj.jinhua.gov.cn
        executableClient.setDomainName(domainName);
        executableClient.setProtocal("https");
        //应用App Key
        executableClient.setAccessKey(appKey);
        //应用App Secret
        executableClient.setSecretKey(appSecret);
        executableClient.init();
    }
}
